package endoscopic

import (
	"fmt"
	"rongyy/src/app"
	"rongyy/src/middlewares"
	"rongyy/src/models"
)

type FollowUp struct {
	models.BaseModel `xorm:"extends"`
	InfoId           int64  `xorm:"info_id" json:"info_id"`
	Name             string `xorm:"name" json:"name"`
	IsEsd            string `xorm:"is_esd" json:"is_esd"`
	Remark           string `xorm:"remark" json:"remark"`
}

func (pm *FollowUp) TableName() string {
	return "endoscopic_patient_follow_up"
}

func (pm *FollowUp) Insert() error {
	_, err := app.DB().Insert(pm)
	if err != nil {
		middlewares.Logger.Println("ERROR - FollowUp Insert failed ", err)
		return err
	}
	return nil
}

func (pm *FollowUp) SelectById(id int64) (*FollowUp, error) {
	am := &FollowUp{}
	has, err := app.DB().Where("id = ? ", id).Limit(1).Get(am)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return am, nil
}

func (pm *FollowUp) Update(req *FollowUp) error {
	_, err := app.DB().ID(req.Id).Cols("name").Update(req)
	if err != nil {
		middlewares.Logger.Println("ERROR - FollowUp Update failed ", err)
		return fmt.Errorf("更新失败")
	}
	return nil
}

func (pm *FollowUp) SelectByInfoId(infoId int64) ([]FollowUp, error) {
	data := make([]FollowUp, 0)
	s := app.DB().Table("endoscopic_patient_follow_up")
	s.Where("info_id=?", infoId)

	total, err := s.Asc("created_at").FindAndCount(&data)
	middlewares.Logger.Println("total:", total)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (ss *FollowUp) DeleteById(req *FollowUp) error {
	_, err := app.DB().ID(req.Id).Delete(req)
	if err != nil {
		middlewares.Logger.Println("ERROR - FollowUp delete failed ", err)
		return fmt.Errorf("更新失败")
	}
	return nil
}
